package sfeir.ergosum;

import java.util.List;

import sfeir.ergosum.model.spreadsheet.SpreadsheetEntry;
import sfeir.ergosum.service.BackUpService;
import sfeir.ergosum.tools.SpreadsheetClient;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class RestoreBackUpActivity extends ListActivity {

    //private static final int DIALOG_CREATE_OR_SELECT = 0;
    private SharedPreferences mPrefs;
    private ProgressDialog mProgress;
    private SpreadsheetClient mSpreadsheetClient = new SpreadsheetClient(
            new SpreadsheetClient.ResponseHandler() {
                @SuppressWarnings("unchecked")
                @Override
                public void handleMessage(Message msg) {
                    if (mFinished)
                        return;
                    switch (msg.what) {
                    case R.id.httpclient_ready:
                        mProgress.setMessage(getString(R.string.authenticating));
                        mProgress.setProgress(1000);

                        String ids = mPrefs.getString(
                                "preference_loginpassKey", " \n ");
                        String[] values = new String[2];
                        values = ids.split("\n");
                        mSpreadsheetClient.setUserCredentials(values[0],
                                values[1]);

                        mSpreadsheetClient.handler.obtainMessage(
                                R.id.request_login, R.id.client_auth_success,
                                0, "wise").sendToTarget();
                        break;
                    case R.id.client_get_spreadsheets:
                        mSpreadsheetEntries = (List<SpreadsheetEntry>) msg.obj;
                        mProgress.dismiss();
                        for (SpreadsheetEntry key : mSpreadsheetEntries) {
                            if (key.getTitle().contains("HiveGotContact Backup")) {
                                mAdapter.add(key);
                            }
                        }
                        mSpreadsheetClient.terminate();
                        mSpreadsheetClient = null;
                        mAdapter.notifyDataSetChanged();
                        break;
                    case R.id.client_auth_success:
                        mProgress
                                .setMessage(getString(R.string.listing_spreadsheets));
                        mProgress.setProgress(6000);
                        mSpreadsheetClient.handler.obtainMessage(
                                R.id.request_spreadsheets)
                                .sendToTarget();
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                    }
                }
            });
    private ArrayAdapter<SpreadsheetEntry> mAdapter;
    private List<SpreadsheetEntry> mSpreadsheetEntries;
    private boolean mFinished;

    public static void actionRestoreBackup(Context context) {
        Intent i = new Intent();
        i.setClass(context, RestoreBackUpActivity.class);
        context.startActivity(i);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mProgress = ProgressDialog.show(this, getString(R.string.backup_restore_contact), "", false,
                true, new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        if (null != mSpreadsheetClient
                                && mSpreadsheetClient.isAlive())
                            mSpreadsheetClient.terminate();
                        finish();
                    }
                });
        mAdapter = new ArrayAdapter<SpreadsheetEntry>(this,
                android.R.layout.simple_list_item_1);
        setListAdapter(mAdapter);
        setContentView(R.layout.restore_select_list);
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String ids = mPrefs.getString("preference_loginpassKey", " \n ");
        String[] values = ids.split("\n");
        

        if (values.length != 2 || " ".equals(values[0]) || " ".equals(values[1])) {
            new AlertDialog.Builder(this).setIcon(
                    android.R.drawable.stat_notify_error).setMessage(
                    getString(R.string.profile_fill_in_authentification)).setPositiveButton(
                    getString(R.string.preference_go_to_pref_screen),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PreferencesActivity.startPreferenceActionAuthentification(RestoreBackUpActivity.this);
                            if (null != mSpreadsheetClient
                                    && mSpreadsheetClient.isAlive())
                                mSpreadsheetClient.terminate();
                            finish();
                        }
                    }).setCancelable(true).setOnCancelListener(
                    new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            if (null != mSpreadsheetClient
                                    && mSpreadsheetClient.isAlive())
                                mSpreadsheetClient.terminate();
                            finish();
                        }
                    }).show();
            // Toast.makeText(this, "Fill in you credentials first", 3000);
            return;
        }
        if (null != mSpreadsheetClient && !mSpreadsheetClient.isAlive())
            mSpreadsheetClient.start();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        SpreadsheetEntry selectedEntry = mAdapter.getItem(position);//mSpreadsheetEntries.get(position);
        String key = selectedEntry.getId();
        key = key.substring(key.lastIndexOf('/') + 1);
        BackUpService.actionRestore(RestoreBackUpActivity.this, key);
        finish();
    }

    @Override
    public void finish() {
        mFinished = true;
        super.finish();
    }
}
